package org.dragonnova.meetingserver.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import org.dragonnova.meetingserver.model.bean.DeviceInfo;
import org.dragonnova.meetingserver.model.bean.MeetingInfo;
import org.dragonnova.meetingserver.model.bean.VoiceInfo;

import java.util.ArrayList;


/**
 * Created by hucn on 2016/1/10.
 * Description:一个用于封装contentresolver查询方法的工具类
 */
public class ContentResolverUtil {
    private Context mContext;
    private ContentResolver mResolver;

    public ContentResolverUtil(Context context) {
        this.mContext = context;
        mResolver = mContext.getContentResolver();
    }

    /**
     * 保存聊天记录
     */
    public int insertChatHistory(VoiceInfo bean) {
        /*String orgContent, String tranContent,long inserttime, char type,
                        String orgPath,int orgCosttime, String userId,int flag*/
        ContentValues cv = new ContentValues();
        cv.put(VoiceInfo.KEY_ORG_TRAN_TEXT_COLUMN, bean.getOrgContent());
        cv.put(VoiceInfo.KEY_TRAN_TEXT_COLUMN, bean.getTranContent());
        cv.put(VoiceInfo.KEY_INSERT_DATE_COLUMN, bean.getInsertTime());
        cv.put(VoiceInfo.KEY_VOICE_TYPE_COLUMN, String.valueOf(bean.getType()));
        cv.put(VoiceInfo.KEY_ORG_PATH_COLUMN, bean.getOrgPath());
        cv.put(VoiceInfo.KEY_VOICE_ORG_COST_TIME_COLUMN, bean.getOrgCostTime());
        cv.put(VoiceInfo.KEY_VOICE_USER_ID_FOREIGN_COLUMN, bean.getUserId());
        cv.put(VoiceInfo.KEY_VOICE_FLAG_COLUMN, bean.getFlag());
        Uri resultUri = mResolver.insert(VoiceInfo.CONTENT_VOICE_URI, cv);
        return getInsertResultInUri(resultUri);
    }

    /**
     * 查询聊天记录
     */
    public ArrayList<VoiceInfo> findHistory(String id) {
        Uri ContentUris = VoiceInfo.CONTENT_VOICE_URI;
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        Cursor cursor = mResolver.query(uri, null, "USER_ID=? and FLAG=?", new String[]{id, "1"}, null);
        ArrayList<VoiceInfo> listinfos = new ArrayList<>();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long _id = cursor.getLong(cursor.getColumnIndex(VoiceInfo.KEY_ID_COLUMN));
                String orgContent = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_ORG_TRAN_TEXT_COLUMN));
                String tranContent = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_TRAN_TEXT_COLUMN));
                long inserttime = cursor.getLong(cursor.getColumnIndex(VoiceInfo.KEY_INSERT_DATE_COLUMN));
                char type = (cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_TYPE_COLUMN))).charAt(0);
                String orgPath = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_ORG_PATH_COLUMN));
                int orgCosttime = cursor.getInt(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_ORG_COST_TIME_COLUMN));
                String userId = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_USER_ID_FOREIGN_COLUMN));
                int flag = cursor.getInt(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_FLAG_COLUMN));
                VoiceInfo voiceInfo = new VoiceInfo(_id, orgContent, tranContent, inserttime, type, orgPath, orgCosttime, userId, flag);
                listinfos.add(voiceInfo);
            }
            cursor.close();
            return listinfos;
        }
        return null;
    }

    /**
     * 删除聊天记录
     */
    public int deleteAllChatHistory(String userId) {
        return mResolver.delete(VoiceInfo.CONTENT_VOICE_URI, "USER_ID=?", new String[]{userId});
    }

    /**
     * 根据id删除聊天记录
     */
    public int deleteChatHistoryById(String userId, long id) {
        return mResolver.delete(VoiceInfo.CONTENT_VOICE_URI, "_id=? and USER_ID=?", new String[]{String.valueOf(id), userId});
    }

    /**
     * 插入meeting记录
     */
    public int insertMeeting(MeetingInfo bean) {
        ContentValues cv = new ContentValues();
        cv.put(MeetingInfo.KEY_SERIAL_COLUMN, bean.getSerial());
        cv.put(MeetingInfo.KEY_START_TIME_COLUMN, bean.getStartTime());
        cv.put(MeetingInfo.KEY_END_TIME_COLUMN, bean.getEndTime());
        cv.put(MeetingInfo.KEY_DURATION_COLUMN, bean.getDuration());
        cv.put(MeetingInfo.KEY_NAME_COLUMN, bean.getName());
        cv.put(MeetingInfo.KEY_PASSWORD_COLUMN, bean.getPassword());
        cv.put(MeetingInfo.KEY_FLAG_COLUMN, bean.getFlag());
        Uri resultUri = mResolver.insert(MeetingInfo.CONTENT_MEETING_URI, cv);
        return getInsertResultInUri(resultUri);
    }

    /**
     * 更新meeting记录
     */
    public int updataMeeting(MeetingInfo bean) {
        Uri ContentUris = MeetingInfo.CONTENT_MEETING_URI;
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        ContentValues cv = new ContentValues();
        cv.put(MeetingInfo.KEY_SERIAL_COLUMN, bean.getSerial());
        cv.put(MeetingInfo.KEY_START_TIME_COLUMN, bean.getStartTime());
        cv.put(MeetingInfo.KEY_END_TIME_COLUMN, bean.getEndTime());
        cv.put(MeetingInfo.KEY_DURATION_COLUMN, bean.getDuration());
        cv.put(MeetingInfo.KEY_NAME_COLUMN, bean.getName());
        cv.put(MeetingInfo.KEY_PASSWORD_COLUMN, bean.getPassword());
        cv.put(MeetingInfo.KEY_FLAG_COLUMN, bean.getFlag());
        int result = mResolver.update(uri, cv, "SERIAL=?", new String[]{String.valueOf(bean.getSerial())});
        return result;
    }

    /**
     * 查询会议记录
     */
    public MeetingInfo findLatestMeeting() {
        Uri ContentUris = MeetingInfo.CONTENT_MEETING_URI;
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        Cursor cursor1 = mResolver.query(uri, null, null, null, null);
        MeetingInfo meetingInfo = null;
        if (cursor1 != null) {
            if (cursor1.moveToLast()) {
                long latestId = cursor1.getLong(cursor1.getColumnIndex(MeetingInfo.KEY_ID_COLUMN));
                Cursor cursor2 = mResolver.query(uri, null, "_id=?", new String[]{String.valueOf(latestId)}, null);
                if (cursor2 != null) {
                    cursor2.moveToNext();
                    long id = cursor2.getLong(cursor2.getColumnIndex(MeetingInfo.KEY_ID_COLUMN));
                    long serial = cursor2.getLong(cursor2.getColumnIndex(MeetingInfo.KEY_SERIAL_COLUMN));
                    long startTime = cursor2.getLong(cursor2.getColumnIndex(MeetingInfo.KEY_START_TIME_COLUMN));
                    long endTime = cursor2.getLong(cursor2.getColumnIndex(MeetingInfo.KEY_END_TIME_COLUMN));
                    long duration = cursor2.getLong(cursor2.getColumnIndex(MeetingInfo.KEY_DURATION_COLUMN));
                    String name = cursor2.getString(cursor2.getColumnIndex(MeetingInfo.KEY_NAME_COLUMN));
                    String password = cursor2.getString(cursor2.getColumnIndex(MeetingInfo.KEY_PASSWORD_COLUMN));
                    int flag = cursor2.getInt(cursor2.getColumnIndex(MeetingInfo.KEY_FLAG_COLUMN));
                    meetingInfo = new MeetingInfo(id, serial, startTime, endTime, duration, name, password, flag);
                    cursor2.close();
                }
            }
            cursor1.close();
        }
        return meetingInfo;
    }

    /**
     * 查询会议记录
     */
    public ArrayList<MeetingInfo> findAllMeeting() {
        Uri ContentUris = MeetingInfo.CONTENT_MEETING_URI;
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        Cursor cursor = mResolver.query(uri, null, null, null, null);
        ArrayList<MeetingInfo> listinfos = new ArrayList<>();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndex(MeetingInfo.KEY_ID_COLUMN));
                long serial = cursor.getLong(cursor.getColumnIndex(MeetingInfo.KEY_SERIAL_COLUMN));
                long startTime = cursor.getLong(cursor.getColumnIndex(MeetingInfo.KEY_START_TIME_COLUMN));
                long endTime = cursor.getLong(cursor.getColumnIndex(MeetingInfo.KEY_END_TIME_COLUMN));
                long duration = cursor.getLong(cursor.getColumnIndex(MeetingInfo.KEY_DURATION_COLUMN));
                String name = cursor.getString(cursor.getColumnIndex(MeetingInfo.KEY_NAME_COLUMN));
                String password = cursor.getString(cursor.getColumnIndex(MeetingInfo.KEY_PASSWORD_COLUMN));
                int flag = cursor.getInt(cursor.getColumnIndex(MeetingInfo.KEY_FLAG_COLUMN));
                MeetingInfo meetingInfo = new MeetingInfo(id, serial, startTime, endTime, duration, name, password, flag);
                listinfos.add(meetingInfo);
            }
            cursor.close();
            return listinfos;
        }
        return null;
    }

    /**
     * 根据meeting id 查询聊天记录
     */
    /*public ArrayList<VoiceInfo> findHistoryByMeeting(String meetingid) {
        Uri ContentUris = Uri.parse(VoiceInfo.CONTENT_VOICE_URI.toString() + "/" + "meeting");
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        Cursor cursor = mResolver.query(uri, null, "MEETING_ID=?", new String[]{meetingid}, null);
        ArrayList<VoiceInfo> listinfos = new ArrayList<>();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndex(VoiceInfo.KEY_ID_COLUMN));
                String orgContent = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_ORG_TRAN_TEXT_COLUMN));
                String tranContent = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_TRAN_TEXT_COLUMN));
                long inserttime = cursor.getLong(cursor.getColumnIndex(VoiceInfo.KEY_INSERT_DATE_COLUMN));
                char type = (cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_TYPE_COLUMN))).charAt(0);
                String orgPath = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_ORG_PATH_COLUMN));
                int orgCosttime = cursor.getInt(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_ORG_COST_TIME_COLUMN));
                String userId = cursor.getString(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_USER_ID_FOREIGN_COLUMN));
                int flag = cursor.getInt(cursor.getColumnIndex(VoiceInfo.KEY_VOICE_FLAG_COLUMN));
                long meetingId = cursor.getLong(cursor.getColumnIndex(VoiceInfo.KEY_MEETING_ID_COLUMN));
                VoiceInfo voiceInfo = new VoiceInfo(id, orgContent, tranContent, inserttime, type, orgPath, orgCosttime, userId, flag, meetingId);
                listinfos.add(voiceInfo);
            }
            cursor.close();
            return listinfos;
        }
        return null;
    }*/

    /**
     * 插入设备记录
     */
    public int insertDevice(DeviceInfo bean) {
        ContentValues cv = new ContentValues();
        cv.put(DeviceInfo.KEY_HOSTID_COLUMN, bean.getHostId());
        cv.put(DeviceInfo.KEY_HOSTNAME_COLUMN, bean.getHostName());
        cv.put(DeviceInfo.KEY_WIFIADDR_COLUMN, bean.getWifiAddr());
        cv.put(DeviceInfo.KEY_WIFISTATUS_COLUMN, bean.getWifiStatus().ordinal());
        cv.put(DeviceInfo.KEY_LANGUAGE_COLUMN, String.valueOf(bean.getLanguage()));
        cv.put(DeviceInfo.KEY_PORT_COLUMN, bean.getPort());
        cv.put(DeviceInfo.KEY_FLAG_COLUMN, 1);
        Uri resultUri = mResolver.insert(DeviceInfo.CONTENT_DEVICE_URI, cv);
        return getInsertResultInUri(resultUri);
    }

    /**
     * 看设备是否存在
     */
    public boolean isDeviceExist(String hostId) {
        boolean isExist;
        Uri ContentUris = DeviceInfo.CONTENT_DEVICE_URI;
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        Cursor cursor = mResolver.query(uri, null, "HOSTID=?", new String[]{hostId}, null);
        isExist = cursor != null && cursor.moveToNext();
        if (cursor != null) cursor.close();
        return isExist;
    }

    /**
     * 查询聊天记录
     */
    public ArrayList<DeviceInfo> findConnectedDevices() {
        Uri ContentUris = DeviceInfo.CONTENT_DEVICE_URI;
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        Cursor cursor = mResolver.query(uri, null, "WIFISTATUS=?", new String[]{"0"}, null);
        ArrayList<DeviceInfo> listinfos = new ArrayList<>();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long _id = cursor.getLong(cursor.getColumnIndex(DeviceInfo.KEY_ID_COLUMN));
                String hostId = cursor.getString(cursor.getColumnIndex(DeviceInfo.KEY_HOSTID_COLUMN));
                String hostName = cursor.getString(cursor.getColumnIndex(DeviceInfo.KEY_HOSTNAME_COLUMN));
                String wifiAddr = cursor.getString(cursor.getColumnIndex(DeviceInfo.KEY_WIFIADDR_COLUMN));
                int wifiStatus = (cursor.getInt(cursor.getColumnIndex(DeviceInfo.KEY_WIFISTATUS_COLUMN)));
                char language = cursor.getString(cursor.getColumnIndex(DeviceInfo.KEY_LANGUAGE_COLUMN)).charAt(0);
                int port = cursor.getInt(cursor.getColumnIndex(DeviceInfo.KEY_PORT_COLUMN));
                int flag = cursor.getInt(cursor.getColumnIndex(DeviceInfo.KEY_FLAG_COLUMN));
                DeviceInfo.Status status = DeviceInfo.Status.DisConnected;
                if (wifiStatus == 0) status = DeviceInfo.Status.Connected;
                DeviceInfo deviceInfo = new DeviceInfo(hostId, hostName, wifiAddr, status, language, port);
                listinfos.add(deviceInfo);
            }
            cursor.close();
            return listinfos;
        }
        return null;
    }

    public int updataDevice(DeviceInfo bean) {
        Uri ContentUris = DeviceInfo.CONTENT_DEVICE_URI;
        Uri uri = Uri.withAppendedPath(ContentUris, "");
        ContentValues cv = new ContentValues();
        cv.put(DeviceInfo.KEY_HOSTID_COLUMN, bean.getHostId());
        cv.put(DeviceInfo.KEY_HOSTNAME_COLUMN, bean.getHostName());
        cv.put(DeviceInfo.KEY_WIFIADDR_COLUMN, bean.getWifiAddr());
        cv.put(DeviceInfo.KEY_WIFISTATUS_COLUMN, bean.getWifiStatus().ordinal());
        cv.put(DeviceInfo.KEY_LANGUAGE_COLUMN, String.valueOf(bean.getLanguage()));
        cv.put(DeviceInfo.KEY_PORT_COLUMN, bean.getPort());
        cv.put(DeviceInfo.KEY_FLAG_COLUMN, 1);
        int result = mResolver.update(uri, cv, "HOSTID=?", new String[]{bean.getHostId()});
        return result;
    }

    /**
     * 根据hostid删除设备信息
     */
    public int deleteDevice(String hostId) {
        return mResolver.delete(DeviceInfo.CONTENT_DEVICE_URI, "HOSTID=?", new String[]{hostId});
    }


    /**
     * 获取insert返回uri的最后拼接的insert返回值
     */
    private int getInsertResultInUri(Uri uri) {
        String uriStr = uri.toString();
        int lastIndexOf = uriStr.lastIndexOf("/");
        String insertResult = uriStr.substring(lastIndexOf + 1);
        try {
            return Integer.valueOf(insertResult);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return -1;
        }
    }
}
